﻿@using SmartStore.AmazonPay
@model SmartStore.AmazonPay.Models.AmazonPayViewModel
@{
	Html.AddCssFileParts(true, Url.Content("~/Plugins/SmartStore.AmazonPay/Content/SmartStore.AmazonPay.css"));
    Html.AddScriptParts(true, "~/Plugins/SmartStore.AmazonPay/Scripts/jquery.deserialize.js");
}

<script>
	window.onAmazonLoginReady = function () {
		try {
			amazon.Login.setClientId('@Html.Raw(Model.ClientId)');
		}
		catch (e) {
			console.log(e);
		}
	};

	window.onAmazonPaymentsReady = function () {
		try {
			new OffAmazonPayments.Widgets.AddressBook({
				sellerId: '@Model.SellerId',
				amazonOrderReferenceId: '@Model.OrderReferenceId',
				displayMode: 'Read',
				design: {
					designMode: 'responsive'
				},
				onError: function (e) {
					console.log(e.getErrorCode() + ': ' + e.getErrorMessage());
				}
			}).bind('amazon-pay-read-address-book-widget');
		}
		catch (e) {
			console.log(e);
		}

		try {
			new OffAmazonPayments.Widgets.Wallet({
				sellerId: '@Model.SellerId',
				amazonOrderReferenceId: '@Model.OrderReferenceId',
				displayMode: 'Read',
				design: {
					designMode: 'responsive'
				},
				onError: function (e) {
					console.log(e.getErrorCode() + ': ' + e.getErrorMessage());
				}
			}).bind('amazon-pay-read-wallet-widget');
		}
		catch (e) {
			console.log(e);
		}
    };

    $(function () {
        // Confirmation flow.
        $(document).on('submitOrder', function (e) {
            var isConfirmed = @(Model.IsConfirmed.ToString().ToLower());
            e.isOrderValid = isConfirmed;

            // Confirm order.
            if (!isConfirmed) {
                var data = $('#confirm-order-form').serializeArray();

                e.disableBuyButton = true;

                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("ConfirmOrder", "AmazonPayCheckout", new { area = AmazonPayPlugin.SystemName })',
                    data: { "formData": JSON.stringify(data) },
                    success: function (response) {
                        if (response.success) {
                            OffAmazonPayments.triggerPostOrderFlow('@Model.SellerId', '@Model.OrderReferenceId');
                        }
                        else if (!_.isEmpty(response.redirectUrl)) {
                            // Handled server side. Reject AmazonPay and redirect to payment list.
                            window.location = response.redirectUrl;
                        }
                        else if (!_.isEmpty(response.messages)) {
                            var errorEvent = jQuery.Event('reportError');
                            errorEvent.message = response.messages
                            $(document).trigger(errorEvent);
                        }
                    },
                    error: function (objXml) {
                        if (objXml != null && objXml.responseText != null && objXml.responseText !== '') {
                            displayNotification(objXml.responseText, 'error');
                        }
                    }
                });
            }
        });

        // Restore form data.
        @if (Model.IsConfirmed && Model.FormData.HasValue())
        {
            <text>
            try {
                var data = @Html.Raw(Model.FormData);
                $('#confirm-order-form').deserialize(data);
            }
            catch (e) {
                console.log('Failed to restore form data.');
                console.log(e);
            }
            </text>
        }

        // Fire event to simulate buy button click.
        @if (Model.SubmitForm)
        {
            <text>
            jQuery(document).ready(function () {
                var clickBuyButtonEvent = jQuery.Event('clickBuyButton');
                clickBuyButtonEvent.customerAgreed = true;
                clickBuyButtonEvent.showThrobber = true;

                $(document).trigger(clickBuyButtonEvent);
            });
            </text>
        }
    });
</script>
<script async="async" src="@Html.Raw(Model.WidgetUrl)"></script>
